package org.example.weather.bigscreen.portal.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import lombok.extern.slf4j.Slf4j;
import org.example.weather.bigscreen.core.api.dto.AreaDTO;
import org.example.weather.bigscreen.core.api.dto.BaiduWeatherDTO;
import org.example.weather.bigscreen.core.api.dto.WeatherInfoDTO;
import org.example.weather.bigscreen.portal.client.BaiduWeatherClient;
import org.example.weather.bigscreen.portal.client.CoreAreaClient;
import org.example.weather.bigscreen.portal.client.CoreWeatherClient;
import org.example.weather.bigscreen.portal.client.WeatherAreaClient;

import org.example.weather.bigscreen.portal.dto.*;
import org.example.weather.bigscreen.portal.utils.MockUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created on 2022-07-22.
 * https://cloud.baidu.com/product/sugar.html
 *
 * @author chenyu
 */
@RestController
@Slf4j
@Api(value = "大屏信息", tags = {"大屏信息"})
@RequestMapping("bigscreen")
public class BigScreenController {


    private CoreAreaClient coreAreaClient;
    private CoreWeatherClient coreWeatherClient;
    private BaiduWeatherClient baiduWeatherClient;
    private Random random = new Random();

    @Value("${api.baidu.weather.dataType:all}")
    private String dataType;
    @Value("${api.baidu.weather.ak:m4rcfGdiZUvq4ug8MiYlnPFS7oV2vtng}")
    private String ak;


    public BigScreenController(final CoreAreaClient coreAreaClient, final CoreWeatherClient coreWeatherClient,final BaiduWeatherClient baiduWeatherClient) {
        this.coreAreaClient = coreAreaClient;
        this.coreWeatherClient = coreWeatherClient;
        this.baiduWeatherClient = baiduWeatherClient;
    }

    @GetMapping("area/{areaId}/name")
    @ApiOperation(value = "指定id获取地区名称", httpMethod = "GET")
    @ApiResponse(code = 200, message = "接口返回成功")
    public String getAreaName(@PathVariable("areaId") String areaId) {
        return coreAreaClient.selectById(areaId).getAreaName();
    }

    @GetMapping("map")
    @ApiOperation(value = "全国地图", httpMethod = "GET")
    @ApiResponse(code = 200, message = "接口返回成功")
    public BigScreenResponseDTO<BigScreenMapDataDTO> map() {
        List<AreaDTO> areaDTOS = coreAreaClient.selectByLevel(0);
        List<BigScreenMapDTO> mapDTOS = new LinkedList<>();
        String cityId;
        for(int i=0;i<areaDTOS.size();i++){
            AreaDTO areaDTO = areaDTOS.get(i);
            String id = areaDTO.getAreaId();
            if ("820000".equals(id) || "810000".equals(id)) {
                cityId = "719001";
            } else if ("710000".equals(id)) {

                cityId = "719001";
            } else {
                cityId = id.substring(0, 2) + "0100";
            }
            WeatherInfoDTO select = coreWeatherClient.selectAreaHistory(null, new Date(), cityId);
            List<BigDecimal> tooltipValues = new ArrayList<>();
            tooltipValues.add(select.getTempLow());
            tooltipValues.add(select.getTempHigh());
            BigScreenMapDTO mapDTO = new BigScreenMapDTO(areaDTO.getAreaName(),areaDTO.getAreaId(),select.getTemp().intValue(),select.getFeelsLike().intValue(),4,tooltipValues,"sugar.baidu.com");
            mapDTOS.add(mapDTO);
        }
        BigScreenMapDataDTO data = new BigScreenMapDataDTO(mapDTOS,"平均温度","当前温度","级别",Arrays.asList("省内最低温度", "省内最高温度"),Arrays.asList("度", "度"));
        BigScreenResponseDTO result = new BigScreenResponseDTO(0,"",data);
        return result;
    }

    @GetMapping("provinceMap")
    @ApiOperation(value = "省市级地图", httpMethod = "GET")
    @ApiResponse(code = 200, message = "接口返回成功")
    public BigScreenResponseDTO<BigScreenMapDataDTO> provinceMap(@RequestParam(value = "areaId", required = false, defaultValue = "321000") String areaId) {
        List<AreaDTO> areaDTOS = coreAreaClient.selectByParentId(areaId);
        if (areaDTOS.size() == 1) {
            areaDTOS = coreAreaClient.selectByParentId(areaDTOS.get(0).getAreaId());
        }
        List<BigScreenMapDTO> provDates = new LinkedList<>();
        for (int i = 0; i < areaDTOS.size(); i++) {
            AreaDTO areaDTO = areaDTOS.get(i);

            WeatherInfoDTO weatherInfo = coreWeatherClient.selectAreaHistory(null, new Date(), areaDTO.getAreaId());
            LinkedList<BigDecimal> tooltipValues = new LinkedList<>();
            tooltipValues.add(weatherInfo.getTempLow());
            tooltipValues.add(weatherInfo.getTempHigh());
            BigScreenMapDTO provDate = new BigScreenMapDTO(areaDTO.getAreaName(),areaDTO.getAreaId(),weatherInfo.getTemp().intValue(),weatherInfo.getTemp().intValue(),4,tooltipValues,"sugar.baidu.com");
            provDates.add(provDate);
        }
        BigScreenMapDataDTO data = new BigScreenMapDataDTO(provDates,"当前温度","温度","级别",Arrays.asList("最低温度", "最高温度"),Arrays.asList("度", "度"));
        BigScreenResponseDTO result = new BigScreenResponseDTO(0,"",data);
        return result;
    }

    @GetMapping("forecasts")
    @ApiOperation(value = "天气预报", httpMethod = "GET")
    @ApiResponse(code = 200, message = "接口返回成功")
    public BigScreenResponseDTO<BigScreenTrendDayDTO> forecasts(@RequestParam(value = "areaId", required = false, defaultValue = "321000") String areaId) {
        AreaDTO areaDTO = coreAreaClient.selectById(areaId);
        List<BaiduWeatherForecastsDTO> forecasts = baiduWeatherClient.fetchWeather(areaDTO.getAreaId(), dataType, ak).getResult().getForecasts();
        List<Date> categories = new ArrayList<>();
        for (int i = 0; i < forecasts.size(); i++) {
            categories.add(forecasts.get(i).getDate());
        }
        List<BigScreenSeriesDTO> series =  new ArrayList<>();
        List<BigDecimal> highData = new ArrayList<>();
        for (int i = 0; i < forecasts.size(); i++) {
            highData.add(new BigDecimal(forecasts.get(i).getHigh()));
        }
        BigScreenSeriesDTO highTmp = new BigScreenSeriesDTO("最高温度",highData);
        List<BigDecimal> lowData = new ArrayList<>();
        for (int i = 0; i < forecasts.size(); i++) {
            lowData.add(new BigDecimal(forecasts.get(i).getLow()));
        }
        BigScreenSeriesDTO lowTmp = new BigScreenSeriesDTO("最低温度",lowData);
        series.add(highTmp);
        series.add(lowTmp);
        BigScreenTrendDayDTO data = new BigScreenTrendDayDTO();
        data.setCategories(categories);
        data.setSeries(series);
        BigScreenResponseDTO result = new BigScreenResponseDTO(0,"",data);
        return result;

    }
    @GetMapping("forecasts/text")
    @ApiOperation(value = "天气预报的text标题文本", httpMethod = "GET")
    @ApiResponse(code = 200, message = "接口返回成功")
    public BigScreenResponseDTO<String> forecastsText(@RequestParam(value = "areaId", required = false, defaultValue = "321000") String areaId) {
        AreaDTO parent = coreAreaClient.selectParent(areaId);
        AreaDTO areaDTO = coreAreaClient.selectById(areaId);
        BigScreenResponseDTO result = new BigScreenResponseDTO();
        result.setStatus(0);
        result.setMsg("");
        if (areaDTO.getAreaName().equals("北京市") || areaDTO.getAreaName().equals("天津市") || areaDTO.getAreaName().equals("香港") || areaDTO.getAreaName().equals("澳门")) {
            result.setData(areaDTO.getAreaName() + "天气预报");
        } else {
            result.setData(parent.getAreaName() + "-" + areaDTO.getAreaName() + "天气预报");
        }
        return result;
    }

    @GetMapping("trend")
    @ApiOperation(value = "当日天气变化趋势", httpMethod = "GET")
    @ApiResponse(code = 200, message = "接口返回成功")
    public BigScreenResponseDTO<BigScreenTrendHourDTO> trend(@RequestParam(value = "areaId", defaultValue = "321000") String areaId) {
        AreaDTO areaDTO = coreAreaClient.selectById(areaId);
        List<Date> categories = new LinkedList<>();
        List<BigScreenSeriesDTO> series = new LinkedList<>();
        List<WeatherInfoDTO> weatherInfos = coreWeatherClient.selectDaily(new Date(), areaId);
        LinkedList<BigDecimal> temp = new LinkedList<>();
        for (int i = 0; i < weatherInfos.size(); i++) {
            categories.add(weatherInfos.get(i).getUploadTime());
            temp.add(weatherInfos.get(i).getTemp());
        }
        BigScreenSeriesDTO area = new BigScreenSeriesDTO(areaDTO.getAreaName(),temp);
        series.add(area);
        BigScreenTrendHourDTO data = new BigScreenTrendHourDTO(categories,series);
        BigScreenResponseDTO result = new BigScreenResponseDTO(0,"",data);
        return result;
    }

    @GetMapping("subarea")
    @ApiOperation(value = "子地区天气排行", httpMethod = "GET")
    @ApiResponse(code = 200, message = "接口返回成功")
    public BigScreenResponseDTO<BigScreenTableDTO> allsubarea(@RequestParam(value = "areaId", required = false, defaultValue = "320000") String areaId) {
        AreaDTO areaDTO = coreAreaClient.selectById(areaId);
        List<AreaDTO> areaDTOS = coreAreaClient.selectByParentId(areaDTO.getAreaId());
        int total = areaDTOS.size();
        if (total == 1) {
            areaDTOS = coreAreaClient.selectByParentId(areaDTOS.get(0).getAreaId());
            total = areaDTOS.size();
        }
        List<BigScreenTableHeaderDTO> columns = new LinkedList<>();
        BigScreenTableHeaderDTO col1 = new BigScreenTableHeaderDTO("地区","subsys");

        BigScreenTableHeaderDTO col2 = new BigScreenTableHeaderDTO("天气","weather");

        BigScreenTableHeaderDTO col3 = new BigScreenTableHeaderDTO("昨日温度","module");

        BigScreenTableHeaderDTO col4 = new BigScreenTableHeaderDTO("今日温度","business");

        BigScreenTableHeaderDTO col5 = new BigScreenTableHeaderDTO("温度变化","name");
        columns.add(col1);
        columns.add(col2);
        columns.add(col3);
        columns.add(col4);
        columns.add(col5);
        List<BigScreenTableRowDTO> rows = new LinkedList<>();
        for (int i = 0; i < total; i++) {

            WeatherInfoDTO weatherInfo = coreWeatherClient.selectAreaHistory(null, new Date(), areaDTOS.get(i).getAreaId());
            BigScreenTableRowDTO row = new BigScreenTableRowDTO(areaDTOS.get(i).getAreaName(),String.valueOf(weatherInfo.getTemp().intValue()),areaDTOS.get(i).getAreaId(),weatherInfo.getWeatherText(),String.valueOf(weatherInfo.getTemp().intValue()),"保持没变");
            rows.add(row);
        }
        BigScreenTableDTO data = new BigScreenTableDTO();
        data.setTotal(total);
        data.setColumns(columns);
        data.setRows(rows);
        BigScreenResponseDTO result = new BigScreenResponseDTO(0,"",data);
        return result;
    }






}
